<?php

namespace App\Models\CacheModel;

use App\Models\Api\BaseCache;
use AstroTool\Cache\CacheManage;

class AppIndexAbLogData extends BaseCache
{
    protected $table = 'wechat_backup_07_18_14_43_00.app_index_ab_log_data';

    protected $cacheModel = 'index.index_ab_log';

    /**
     * @param int $uid
     * @param int $type 1=>A版 2=>B版
     * @param int $pageType 1=>首页 2=>日运页
     * @return void
     * @throws \Exception
     */
    public function setAbLog(int $uid, int $type, int $pageType)
    {
        if (!in_array($pageType, [1, 2], true))
        {
            return;
        }
        $date = (int)date('Ymd');
        $dataInfo = CacheManage::getInstance()->setCacheConfig($this->cacheModel, "{$uid}:{$date}")->getDataAndSet(function () use ($uid, $date)
        {
            try
            {
                return $this->where(['uid' => $uid, 'date' => $date])->findOrFail()->toArray();
            }
            catch (\Exception $e)
            {
                return [];
            }
        });

        if ($dataInfo)
        {
            $dataInfo = arrayKeyData2int($dataInfo, ['id', 'uid', 'type', 'index', 'fortune_day', 'date', 'index_time', 'fortune_time']);
            $updateData = [];
            if ($pageType === 1)
            {
                if (!$dataInfo['index'])
                {
                    $updateData = [
                        'index' => 1,
                        'index_time' => time(),
                    ];
                }
            } elseif ($pageType === 2)
            {
                if (!$dataInfo['fortune_day'])
                {
                    $updateData = [
                        'fortune_day' => 1,
                        'fortune_time' => time(),
                    ];
                }
            }
            if ($updateData)
            {
                $this->where(['id' => $dataInfo['id']])->update($updateData);
                CacheManage::getInstance()->setCacheConfig($this->cacheModel, "{$uid}:{$date}")->setCache($updateData);
            }
        } else
        {
            $insertData = [
                'uid' => $uid,
                'type' => $type,
                'index' => 0,
                'fortune_day' => 0,
                'date' => $date,
                'index_time' => 0,
                'fortune_time' => 0,
            ];
            if ($pageType === 1)
            {
                $insertData['index'] = 1;
                $insertData['index_time'] = time();
            } elseif ($pageType === 2)
            {
                $insertData['fortune_day'] = 1;
                $insertData['fortune_time'] = time();
            }

            $this->insert($insertData);
            CacheManage::getInstance()->setCacheConfig($this->cacheModel, "{$uid}:{$date}")->rmCache();
        }
    }
}
